package com.xuhaowei.demo.action;



import com.xuhaowei.demo.pojo.Result;
import com.xuhaowei.demo.service.TransferService;
import com.xuhaowei.mvcframework.myannotation.XUAutowired;
import com.xuhaowei.mvcframework.myannotation.XUController;
import com.xuhaowei.mvcframework.myannotation.XURequestMapping;
import com.xuhaowei.mvcframework.myannotation.XUTransactional;
import com.xuhaowei.utils.JsonUtils;
import com.xuhaowei.utils.ProxyUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@XUController
@XURequestMapping("/transfer")
public class DemoAction {
	@XUAutowired
	private TransferService transferService;
	@XUAutowired
	private ProxyUtils proxyUtils;

	private Integer initFlag = 0;

	//初始化方法 用来生成代理类
	private void init(){
		if(initFlag == 1){
			return;
		}else{

			Class<? extends TransferService> aClass = transferService.getClass();
			Boolean interfaceFlag = aClass.isInterface();
			Boolean transactionFlag = aClass.isAnnotationPresent(XUTransactional.class);
			Class<? extends Throwable>[] classes;
			if(transactionFlag){
				classes = aClass.getAnnotation(XUTransactional.class).rollbackFor();
			}else{
				classes = null;
			}
			transferService = (TransferService) proxyUtils.getProxyObject(transferService,interfaceFlag,transactionFlag,classes);

			initFlag = 1;
		}
	}



	@XURequestMapping("/money")
	public void query(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		init();
		// 设置请求体的字符编码
		req.setCharacterEncoding("UTF-8");

		String fromCardNo = req.getParameter("fromCardNo");
		String toCardNo = req.getParameter("toCardNo");
		String moneyStr = req.getParameter("money");
		int money = Integer.parseInt(moneyStr);

		Result result = new Result();

		try {

			// 2. 调用service层方法
			transferService.transfer(fromCardNo,toCardNo,money);
			result.setStatus("200");
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatus("201");
			result.setMessage(e.toString());
		}

		// 响应
		resp.setContentType("application/json;charset=utf-8");
		resp.getWriter().print(JsonUtils.object2Json(result));
	}

}
